import json
from datetime import date

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View

from .models import HeroInfo,BookInfo
# Create your views here.

def index(request):
    book = BookInfo.objects.create_book("abc", date(1980, 1, 1))  #该字段验证了 可以重写create方法  在manager里面把评论等内容添加默认值
    # book=BookInfo.objects.all() #该方法 利用了manager的特性  过滤 已经被删除的书籍
    # print(book.query)
    # # print(book)
    # for i in book:
    #     print(i)
    return HttpResponse("查询数据库")


class BookView(View):
    def get(self,request):
        books=BookInfo.objects.all().filter(is_delete=0)
        data=[]
        for i in books:
            dict={}
            dict['id']=i.id
            dict['btitle']=i.btitle
            dict['bpub_date']=i.bpub_date
            dict['bread']=i.bread
            dict['bcomment']=i.bcomment
            data.append(dict)
        return JsonResponse({"code":200,"msg":"获取数据成功","data":data})
    def post(self,request):
        json_data=request.body.decode()
        data=json.loads(json_data)
        btitle=data.get('btitle')
        bpub_date=data.get('bpub_date')
        bread=data.get('bread')
        bcomment=data.get('bcomment')
        book = BookInfo(btitle=btitle, bpub_date=bpub_date, bread=bread, bcomment=bcomment)
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})
    def put(self,request):
        json_data = request.body.decode()
        data = json.loads(json_data)
        btitle = data.get('btitle')
        bpub_date = data.get('bpub_date')
        bread = data.get('bread')
        bcomment = data.get('bcomment')
        id = data.get('id')
        book = BookInfo.objects.get(id=id)
        book.btitle=btitle
        book.bpub_date=bpub_date
        book.bread=bread
        book.bcomment=bcomment
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})
    def delete(self,request):
        json_data = request.body.decode()
        data = json.loads(json_data)
        id = data.get('id')
        book = BookInfo.objects.get(id=id)
        book.is_delete=True
        book.save()
        return JsonResponse({"code": 200, "msg": "success"})
